
// hisiriDlg.cpp : implementation file
//

#include "stdafx.h"
#include "hisiri.h"
#include "hisiriDlg.h"
#include "afxdialogex.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CAboutDlg dialog used for App About

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// ChisiriDlg dialog




ChisiriDlg::ChisiriDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(ChisiriDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void ChisiriDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(ChisiriDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON2, &ChisiriDlg::OnBnClickedAudio)
	ON_BN_CLICKED(IDC_BUTTON3, &ChisiriDlg::OnBnClickedTest)
	ON_WM_COPYDATA()
END_MESSAGE_MAP()


// ChisiriDlg message handlers

BOOL ChisiriDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here
	m_Audio.m_pDlg = this;
	WakeupInit();
	UpdateView();

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void ChisiriDlg::OnCancel()
{
	m_Audio.CloseInDev();
	m_Audio.CloseOutDev();
	WakeupRelease();
	CDialogEx::OnCancel();
}

void ChisiriDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void ChisiriDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR ChisiriDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}



void ChisiriDlg::OnBnClickedAudio()
{
	if(m_Audio.m_hWaveIn)
	{
		m_Audio.CloseInDev();
		SetDlgItemText(IDC_BUTTON2, L"Audio");
	}
	else
	{
		m_Audio.OpenInDev();
		SetDlgItemText(IDC_BUTTON2, L"Stop");
	}

	UpdateView();
}


void ChisiriDlg::OnBnClickedTest()
{
	CString str;
	GetDlgItemText(IDC_BUTTON3, str);

	if(str == L"Test")
	{
		//SetDlgItemText(IDC_BUTTON3, L"Stop");

		CString strFilter = _T("sample file (*.wav)|*.wav||");
		CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, strFilter);

		if(IDOK == dlg.DoModal())
		{
			CString fn = dlg.GetPathName();

			short wav_buff[HDRCNT*BUFLEN] = {0};

			FILE * fp;
			fopen_s(&fp, CStringA(fn), "r");
			fseek(fp, 44, SEEK_SET);
			fread_s(wav_buff, sizeof(wav_buff), sizeof(short)*BUFLEN, HDRCNT, fp);
			fclose(fp);
			
			ShowIn(wav_buff, HDRCNT*BUFLEN);
			
			float ret = OnFileData(wav_buff, HDRCNT*BUFLEN);

			CString tmp;
			tmp.Format(L"fn=[%s], hi siri=[%f]\r\n", fn, ret);

			CWnd * pWnd = GetDlgItem(IDC_EDIT1);
			pWnd->SetWindowText(tmp);
		}
	}
	else
	{
		SetDlgItemText(IDC_BUTTON3, L"Test");
	}

	UpdateView();
}


void ChisiriDlg::UpdateView()
{
	CString str;

	GetDlgItemText(IDC_BUTTON2, str);
	BOOL isAudioRunning = (str == L"Stop");

	GetDlgItemText(IDC_BUTTON3, str);
	BOOL isTestRunning = (str == L"Stop");

	if(isAudioRunning)
	{
		GetDlgItem(IDC_BUTTON2)->EnableWindow(1);
		GetDlgItem(IDC_BUTTON3)->EnableWindow(0);
	}
	else if(isTestRunning)
	{
		GetDlgItem(IDC_BUTTON2)->EnableWindow(0);
		GetDlgItem(IDC_BUTTON3)->EnableWindow(1);
	}
	else
	{
		GetDlgItem(IDC_BUTTON2)->EnableWindow(1);
		GetDlgItem(IDC_BUTTON3)->EnableWindow(1);
	}
}

extern "C" short gWaveData[BUFLEN*HDRCNT];

BOOL ChisiriDlg::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct)
{
	// TODO: Add your message handler code here and/or call default
	//TRACE("%d\n", ::GetTickCount());
	short * pAudioData = (short*)pCopyDataStruct->lpData;
	int len = pCopyDataStruct->cbData;
	
	ASSERT(len == sizeof(short)*BUFLEN);

	ShowIn(pAudioData, BUFLEN);

	float ret = OnWaveData(pAudioData, BUFLEN);

	if(ret > 0.5f)
	{
		DWORD ts = ::GetTickCount();
		CString tmp;
		tmp.Format(L"ts=[%d], hi siri=[%f]\r\n", ts, ret);
		TRACE("ts=[%d], hi siri=[%f]\r\n", ts, ret);

		CWnd * pWnd = GetDlgItem(IDC_EDIT1);

		CString text;
		pWnd->GetWindowText(text);
		if(text.GetLength() > 256)
			text.Empty();

		text += tmp;
		pWnd->SetWindowText(text);

		SaveSample(gWaveData, sizeof(gWaveData));
	}

	return CDialogEx::OnCopyData(pWnd, pCopyDataStruct);
}

void ChisiriDlg::ShowIn(short * pAudioData, int len)
{
	short * x = pAudioData;
	int N = len;
	
	CRect rc;
	CWnd * pWnd = GetDlgItem(IDC_WAVEIN);
	CDC * dc = pWnd->GetDC();
	pWnd->GetClientRect(&rc);

	CBrush br(RGB(255,255,255));
	dc->FillRect(rc, &br);
	
	dc->MoveTo(0, rc.Height()/2);
	dc->LineTo(rc.Width(), rc.Height()/2);
	
	for(int i=0; i<N; i++)
	{
		int end = (int)(rc.Height()/2 - x[i]/256);
		if(end < 0) end = 0;
		if(end > rc.Height()) end = rc.Height();
		dc->MoveTo(i*rc.Width()/N, rc.Height()/2);
		dc->LineTo(i*rc.Width()/N, end);
	}

	pWnd->ReleaseDC(dc);
}

void ChisiriDlg::SaveSample(short * pAudioData, int len)
{
	CString fn;
	::GetModuleFileName( NULL, fn.GetBuffer(MAX_PATH), MAX_PATH );
	::PathMakePretty(fn.GetBuffer(MAX_PATH));
	::PathRemoveFileSpec(fn.GetBuffer(MAX_PATH));
	fn.ReleaseBuffer();
	fn = fn + _T("\\error"); 
	::CreateDirectory(fn, NULL);

	CTime tm = CTime::GetCurrentTime();
	fn = fn + tm.Format("\\%Y%m%d %H%M%S.wav");
	
	m_Audio.SaveWave(fn, pAudioData, len);
}
